<?php
namespace app\api\controller;
use app\common\controller\ApiBase;
use app\common\model\UserModel;
use app\common\service\LoginService;
use lib\SmsAli;
use think\captcha\facade\Captcha;
use think\exception\ValidateException;
use EasyWeChat\MiniApp\Application;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Db;
use Firebase\JWT\ExpiredException;
use think\facade\Filesystem;
use think\facade\Request;
use Firebase\JWT\SignatureInvalidException;
use zjkal\TimeHelper;//调用时间库
class Login extends ApiBase
{
	 // 学校授权码
	 public function wechatschool(){
	 	$code=$this->request->param('code');//获取前端code
	 	$rawData = input('userInfo'); // 小程序传过来的用户信息
	    $param=$this->request->param();
	 	if(!$code&&empty($code)){
	 		return json(['code'=>404,'msg'=>'code参数缺少']);
	 	}
		// 判断是否授权码登录
		$school=Db::name('school')->where(['id'=>$param['school_id'],'code'=>$param['school_code']])->find();
		if(!$school){
			return json(['code'=>404,'msg'=>'学校授权码错误']);
		}
	 	$app=weconfig();//获取微信配置
	 	$result = $app->getUtils()->codeToSession($code);
	 	if($result['openid']){
	 	    $results=Db::name('member')->where(['openid'=>$result['openid']])->find();
	 	    if(!$results){
	 	        $userinfo['avatarUrl']=$rawData['avatarUrl'];
	 	        $userinfo['openid']=$result['openid'];
	 	        $userinfo['nickName']=$rawData['nickName'];
	 			$userinfo['card']=date('Ymd').TimeHelper::getTimestamp();
				$userinfo['create_time']=TimeHelper::getTimestamp();
	 	        $userinfo['update_time']=TimeHelper::getTimestamp();//可使用time()代替
	 	        $info=Db::name('member')->insert($userinfo);
	 	        $info=Db::name('member')->where(['openid'=>$result['openid']])->find();
	 	    }else{
	 	        Db::name('member')->where(['openid'=>$result['openid']])->update(['update_time'=>TimeHelper::getTimestamp()]);
	 	        $info=Db::name('member')->where(['openid'=>$result['openid']])->find();
	 	    }
			$count=Db::name('usercount')->where(['userid'=>$info['id'],'school_id'=>$school['id']])->find();
			// 判断是否统计登录次数
			if(!$count){
				$re['userid']=$info['id'];
				$re['school_id']=$school['id'];
				$re['create_time']=TimeHelper::getTimestamp();
				$re['number']=1;
				Db::name('usercount')->insert($re);
			}else{
				Db::name('usercount')->where(['userid'=>$info['id'],'school_id'=>$school['id']])->update(['number'=>$count['number']+1,'update_time'=>TimeHelper::getTimestamp()]);
			}
	 		// 判断是否包含https//
	 		if (!isHttpsUrlByRegex($info['avatarUrl'])) {
	 		    $info['avatarUrl']=imgurl($info['avatarUrl']);
	 		}
	 		$token=$this->getTokens($info['id']);
	 		return json(['code'=>200,'msg'=>'登录成功','userinfo'=>$info,'token'=>$token,'school'=>$school['id']]);
	 	}else{
	 		return json(['code'=>404,'msg'=>'获取openid失败']);
	 	}
	 }
     // 微信个人授权获取Openid
	public function wechat(){
		$code=$this->request->param('code');//获取前端code
		$rawData = input('userInfo'); // 小程序传过来的用户信息

		if(!$code&&empty($code)){
			return json(['code'=>404,'msg'=>'code参数缺少']);
		}
		$app=weconfig();//获取微信配置
		$result = $app->getUtils()->codeToSession($code);
		if($result['openid']){
		    $results=Db::name('member')->where(['openid'=>$result['openid']])->find();
		    if(!$results){
		        $userinfo['avatarUrl']=$rawData['avatarUrl'];
		        $userinfo['openid']=$result['openid'];
		        $userinfo['nickName']=$rawData['nickName'];
				$userinfo['card']=date('Ymd').TimeHelper::getTimestamp();
		        $userinfo['create_time']=TimeHelper::getTimestamp();
		        $userinfo['update_time']=TimeHelper::getTimestamp();//可使用time()代替
		        $info=Db::name('member')->insert($userinfo);
		        $info=Db::name('member')->where(['openid'=>$result['openid']])->find();

		    }else{
		        Db::name('member')->where(['openid'=>$result['openid']])->update(['update_time'=>TimeHelper::getTimestamp()]);
		        $info=Db::name('member')->where(['openid'=>$result['openid']])->find();
		    }
			// 判断是否包含https//
			if (!isHttpsUrlByRegex($info['avatarUrl'])) {
			    $info['avatarUrl']=imgurl($info['avatarUrl']);
			}
			$token=$this->getTokens($info['id']);
			return json(['code'=>200,'msg'=>'登录成功','userinfo'=>$info,'token'=>$token]);
		}else{
			return json(['code'=>404,'msg'=>'获取openid失败']);
		}
	}
	  // 更新昵称
	  public  function nickname(){
		  	if(request()->isPost()){
				$param = $this->request->param();
				$member = Db::name('member')->where('id',$param['id'])->find();
				if($member){
					Db::name('member')->where('id',$param['id'])->update(['nickName'=>$param['nickname']]);
					$info=Db::name('member')->where(['id'=>$param['id']])->find();
					$info['avatarUrl']=imgurl($info['avatarUrl']);
					return json(['code'=>200,'msg'=>'更新成功','data'=>$info]);
				}else{
					return json(['code'=>404,'msg'=>'用户不存在']);
				}
			}else{
				return json(['code'=>400,'msg'=>'请求方式错误']);
			}
	  }
	    /**
	     * @param $user_id
	     * @return string
	     */
	    public function getTokens($user_id){
	        $time = TimeHelper::getTimestamp(); //当前时间
	        $token = [
	            'iss' => 'ainiu', //签发者 可选
	            'aud' => 'key', //接收该JWT的一方，可选
	            'iat' => $time, //签发时间
	            'nbf' => $time-1 , //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
	            'exp' => $time+20000, //过期时间,这里设置2个小时
	            'data' => [
	                //自定义信息，不要定义敏感信息
	                'userid' =>$user_id,
	            ]
	        ];
	        return JWT::encode($token, 'ainiukey', 'HS256'); //输出Token  默认'HS256'
	    }
	
	    /**
	     * @param $token
	     */
	    public static function checkToken($token){
	        try {
	            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
	            $decoded = JWT::decode($token, 'ainiukey', ['HS256']); //HS256方式，这里要和签发的时候对应
	            return (array)$decoded;
	        } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
	            return json(['code'=>403,'msg'=>'签名错误']);
	        }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
	            return json(['code'=>401,'msg'=>'token失效']);
	        }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
	            return json(['code'=>401,'msg'=>'token已过期']);
	        }catch(Exception $e) {  //其他错误
	            return json(['code'=>404,'msg'=>'非法请求']);
	        }catch(\UnexpectedValueException $e) {  //其他错误
	            return json(['code'=>404,'msg'=>'非法请求']);
	        } catch(\DomainException $e) {  //其他错误
	            return json(['code'=>404,'msg'=>'非法请求']);
	        }
	
	    }
}